<?php

namespace app\index\controller;

use EasyWeChat\Factory;
use think\App;
use think\Controller;

class Order extends Base
{
    public $wxjsconfig;
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->wxjsconfig=$this->wxbase->jssdk->buildConfig(['chooseWXPay'], $debug = false, $beta = false, $json = true);

    }

    public function index(){
        if($this->isSaveMsg()){
            $user=db('user')->find($this->getUserId());
            $this->assign('user',$user);
        }else{
            $this->assign('user',null);
        }

        $this->assign('wxjsconfig',$this->wxjsconfig);
        return $this->fetch();
    }
    public function order(){
        if(!$this->isLogin()){
            return json(['status'=>0,'msg'=>'请先登录']);
        }
        if(!$this->isSaveMsg()){
            return json(['status'=>0,'msg'=>'请先完善资料']);
        }
        $userId=$this->getUserId();
        $old_order=db('order')->where('order_user_id',$userId)->order('order_ctime desc')->find();
        if((time()-$old_order['order_ctime'])<10){
            return json(['status'=>0,'msg'=>'切勿重复提交订单，10s后下单']);
        }
        $data=input('param.');
        $data['order_user_id']=$userId;
        $data['order_num']=time()+rand(10000,99999);
        $data['order_ctime']=time();
        $data['order_outtime']=time()+60*$data['order_outtime'];
        $saveOrder=db('order')->insert($data);
        if($saveOrder){
            return json(['status'=>1,'msg'=>$data['order_num']]);

        }else{
            return json(['status'=>0,'msg'=>'下单失败']);
        }

    }
    public function pay(){
        $order_num=input('param.order_number');
        $order=db('order')->where('order_num',$order_num)->find();
        $openid=db('user')->where('user_id',$order['order_user_id'])->value('user_openid');
        $res=$this->wxpay->order->unify([
            'body' => '万能新理工-下单',
            'out_trade_no' => $order['order_num'],
            'total_fee' => $order['order_price']*100,
            'notify_url' => 'http://wnxlg.zytec.top/index/order/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        $payconfig=$this->wxpay->jssdk->sdkConfig($res['prepay_id']);
        return json($payconfig);
    }
    public function notify(){
        $response = $this->wxpay->handlePaidNotify(function ($message, $fail) {
            $check=db('order')->where('order_num',$message['out_trade_no'])->find();
            $user=db('user')->find($check['order_user_id']);
            if($check['order_status']==0){
                $res=db('order')->where('order_num',$message['out_trade_no'])->update(['order_status'=>1]);
                if($res){
                    $app = Factory::officialAccount(config('wxconfig'));
                    $tuples=db('user')->where('user_status',2)->select();
                    if($tuples){
                        foreach ($tuples as $k=>$v){
                            $res=$app->template_message->send([
                                'touser' => $v['user_openid'],
                                'template_id' => 'LnPGF9X6sQfWm0xgbGdQfTKwwCefHrMCehl0-ibbYpA',
                                'url' => 'http://wnxlg.zytec.top/index/myorder/showOrder/order_num/'.$check['order_num'],
                                'data' => [
                                    'first' => '有新订单,抓紧接单啦',
                                    'Day' => date('H:i:s',time()),
                                    'orderId'=>$check['order_id'],
                                    'orderType'=>$check['order_title'],
                                    'customerName'=>$user['user_name'],
                                    'customerPhone'=>$user['user_phone'],
                                    'remark'=>'赶快去接单吧'
                                ],
                            ]);
                        }
                    }
                }
            }
            return true;
        });
    }
    public function delOrder(){
        $order_num=input('param.order_num');
        $order=db('order')->where('order_num',$order_num)->find();
        if(!$order){
        	 $this->redirect('myorder/index');
        }
        if($order['order_status']==0){
            $res=db('order')->where('order_num',$order_num)->delete();
            if($res){
                return json(['status'=>1,'msg'=>'ok']);
            }else{
                return json(['status'=>0,'msg'=>'订单删除失败']);
            }
        }else{
            return json(['status'=>0,'msg'=>'订单查询失败']);
        }
    }
    public function tupleOrder(){
        $order_num=input('param.order_num');
        if(!$order_num){
            return $this->error('订单号为空');
        }
        $checkOrder=db('order')->where('order_num',$order_num)->find();
        if($checkOrder['order_status']==0){
            return $this->error('订单未支付');
        }
        if($checkOrder['order_status']>1 || $checkOrder['order_tuple_status']!=0){
            return $this->error('已被接单');
        }
        if(!$this->isLogin()){
            return $this->error('用户未登录');
        }
        $upOrderStatus=db('order')->where('order_num',$order_num)->update(['order_status'=>2]);
        $upOrder=db('order')->where('order_num',$order_num)->update(['order_tuple_status'=>1]);
        if($upOrder){
            $saveData=[
                'tuple_user_id'=>$this->getUserId(),
                'tuple_order_id'=>$checkOrder['order_id'],
                'tuple_ctime'=>time(),
                'tuple_status'=>1
            ];
            $saveTuple=db('tuple')->insert($saveData);
            if($saveData){
                return $this->success('成功接单，赶快配送吧');
            }else{
                return $this->error('注入配送订单失败');
            }
        }else{
            return $this->error('更新订单失败');
        }
    }
    public function overOrder(){
        $order_num=input('param.order_num');
        if(!$order_num){
            return $this->error('订单号为空');
        }
        $checkOrder=db('order')->where('order_num',$order_num)->find();
        if($checkOrder['order_status']==0){
            return $this->error('订单未支付');
        }
        if(!$this->isLogin()){
            return $this->error('用户未登录');
        }
        $saveOrder=db('order')->where('order_num',$order_num)->update(['order_status'=>3,'order_tuple_status'=>2,'order_otime'=>time()]);
        if ($saveOrder){
            $res=db('tuple')->where('tuple_order_id',$checkOrder['order_id'])->update(['tuple_status'=>2]);
            $tupleId=db('tuple')->where('tuple_order_id',$checkOrder['order_id'])->value('tuple_user_id');
            $addMoney=db('user')->where('user_id',$tupleId)->setInc('user_money',$checkOrder['order_price']);
            if($addMoney){
                return json(['status'=>1,'msg'=>'订单配送完成']);
            }else{
                return json(['status'=>0,'msg'=>'更新余额失败']);
            }
        }else{
            return json(['status'=>0,'msg'=>'查询订单失败']);
        }
    }
}
